package com.example.androidframework.ui.course.pkblood

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.databinding.DataBindingUtil
import com.example.androidframework.R
import com.example.androidframework.databinding.ViewPkBloodBinding
import com.martin.lib_base.ktx.loge
import com.xuexiang.xui.utils.DensityUtils
import dev.utils.app.ViewUtils

class PkBloodView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
    private var binding: ViewPkBloodBinding? = null
    // 左侧数值
    var leftNumber: Int = 0
        set(value) {
            field = value
            refreshUI()
        }
    // 右侧数值
    var rightNumber: Int = 0
        set(value) {
            field = value
            refreshUI()
        }
    // 两边的最小固定宽度,避免数字被遮挡
    private val fixedWidth = DensityUtils.dp2px(context, 50f)

    /**
     * 初始化构造方法
     */
    init {
        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.view_pk_blood, this, true)
        refreshUI()
    }

    // 刷新UI
    private fun refreshUI() {
        post {
            binding?.apply {
                // 比例条宽度
                val progressWidth = measuredWidth - fixedWidth * 2
                loge("刷新UI : measuredWidth=$measuredWidth ; progressWidth=$progressWidth ; fixedWidth=$fixedWidth")
                val leftWidth: Int
                val rightWidth: Int
                val total = leftNumber + rightNumber
                if (total == 0) {
                    rightWidth = progressWidth / 2 + fixedWidth
                    leftWidth = measuredWidth - rightWidth
                } else {
                    rightWidth = ((1f * rightNumber / total) * progressWidth).toInt() + fixedWidth
                    leftWidth = measuredWidth - rightWidth
                }
                loge("刷新UI : leftWidth=$leftWidth ; rightWidth=$rightWidth")

                // 设置血条宽度
                ViewUtils.setWidth(vBloodLeft, leftWidth)
                ViewUtils.setWidth(vBloodRight, rightWidth)
                // 设置图片位置
                val params = ivPoint.layoutParams as RelativeLayout.LayoutParams
                params.marginStart = leftWidth - DensityUtils.dp2px(context, 15f)
                ivPoint.layoutParams = params
                // 设置文字
                tvLeft.text = leftNumber.toString()
                tvRight.text = rightNumber.toString()
            }
        }
    }
}